//
//  WJNoDataProtocol.swift
//  PDFSign
//
//  Created by 李永彬 on 2025/10/3.
//

import UIKit
import SnapKit

/// 状态类型
enum WJState {
    case loading
    case noNetwork
    case noData
    case finished
}

// 关联对象键
private struct WJStateDisplayableKeys {
    static var stateView = "wjStateView"
    static var currentState = "wjCurrentState"
}

/// 状态显示协议
protocol WJNoDataProtocol: AnyObject {
    /// 容器视图（状态视图将添加到此视图中）
    var wjStateContainer: UIView { get }
    
    // MARK: - 可自定义属性
    
    /// 各状态对应的图片
    func wjImage(for state: WJState) -> UIImage?
    
    /// 各状态对应的标题
    func wjTitle(for state: WJState) -> String
    
    /// 各状态对应的描述
    func wjMessage(for state: WJState) -> String
    
    /// 各状态对应的按钮标题（返回nil则不显示按钮）
    func wjButtonTitle(for state: WJState) -> String?
    
    /// 各状态视图的frame（默认nil表示填满容器）
    func wjFrame(for state: WJState) -> CGRect?
    
    /// 按钮点击事件
    func wjDidTapStateButton()
}

// MARK: - 默认实现
extension WJNoDataProtocol {
    // MARK: - 状态管理
    var wjCurrentState: WJState {
        get {
            return objc_getAssociatedObject(self, &WJStateDisplayableKeys.currentState) as? WJState ?? .loading
        }
        set {
            objc_setAssociatedObject(self, &WJStateDisplayableKeys.currentState, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    // MARK: - 默认图片
    func wjImage(for state: WJState) -> UIImage? {
        switch state {
        case .loading:
            return UIImage(systemName: "arrow.clockwise")?.withRenderingMode(.alwaysTemplate)
        case .noNetwork:
            return UIImage(systemName: "wifi.slash")?.withRenderingMode(.alwaysTemplate)
        case .noData:
            return UIImage(systemName: "tray.fill")?.withRenderingMode(.alwaysTemplate)
        case .finished:
            return UIImage(systemName: "checkmark.circle.fill")?.withRenderingMode(.alwaysTemplate)
        }
    }
    
    // MARK: - 默认标题
    func wjTitle(for state: WJState) -> String {
        switch state {
        case .loading: return "loading"
        case .noNetwork: return "no network"
        case .noData: return "no data"
        case .finished: return "finished"
        }
    }
    
    // MARK: - 默认描述
    func wjMessage(for state: WJState) -> String {
        switch state {
        case .loading: return "loading"
        case .noNetwork: return "no network"
        case .noData: return "no data"
        case .finished: return "finished"
        }
    }
    
    // MARK: - 默认按钮标题
    func wjButtonTitle(for state: WJState) -> String? {
        switch state {
        case .noNetwork: return "retry"
        case .noData: return "reloadData"
        default: return nil
        }
    }
    
    // MARK: - 默认frame（nil表示填满容器）
    func wjFrame(for state: WJState) -> CGRect? {
        return nil
    }
    
    // MARK: - 状态更新方法
    func wjUpdateState(_ state: WJState) {
        wjCurrentState = state
        wjUpdateStateView()
    }
    
    // MARK: - 私有方法
    private var wjStateView: WJStateView? {
        get {
            return objc_getAssociatedObject(self, &WJStateDisplayableKeys.stateView) as? WJStateView
        }
        set {
            objc_setAssociatedObject(self, &WJStateDisplayableKeys.stateView, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    private func wjUpdateStateView() {
        // 移除旧视图
        wjStateView?.removeFromSuperview()
        
        // 创建新状态视图
        let stateView = WJStateView()
        stateView.wjConfigure(with: self)
        wjStateContainer.addSubview(stateView)
        
        if let frame = wjFrame(for: wjCurrentState) {
            stateView.frame = frame
        } else {
            stateView.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
        }
        
        self.wjStateView = stateView
    }
}

// MARK: - 状态视图
private class WJStateView: UIView {
    private weak var wjDelegate: WJNoDataProtocol?
    
    func wjConfigure(with delegate: WJNoDataProtocol) {
        self.wjDelegate = delegate
        wjSetupUI()
    }
    
    private func wjSetupUI() {
        guard let wjDelegate = wjDelegate else { return }
        let state = wjDelegate.wjCurrentState
        
        backgroundColor = .clear
        
        // 图片视图
        let imageView = UIImageView()
        if let image = wjDelegate.wjImage(for: state) {
            imageView.image = image
//            imageView.tintColor = .clear
            imageView.backgroundColor = .clear
            imageView.contentMode = .scaleAspectFit
            addSubview(imageView)
            
            imageView.snp.makeConstraints { make in
                make.centerX.equalToSuperview()
                make.height.equalTo(182)
                make.width.equalTo(200)
                make.centerY.equalToSuperview().offset(-60)
            }
        }
        
        // 标题标签
        let titleLabel = UILabel()
        titleLabel.text = wjDelegate.wjTitle(for: state)
        titleLabel.font = UIFont.italicSystemFont(ofSize: 14)
        titleLabel.textColor = UIColor(hex: "#121212", alpha: 0.6)
        titleLabel.textAlignment = .center
        addSubview(titleLabel)
        
        titleLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            if imageView.superview != nil {
                make.top.equalTo(imageView.snp.bottom).offset(20)
            } else {
                make.centerY.equalToSuperview().offset(-60)
            }
            make.left.right.equalToSuperview().inset(20)
        }
        
        // 描述标签
        let messageLabel = UILabel()
        messageLabel.text = wjDelegate.wjMessage(for: state)
        messageLabel.font = UIFont.systemFont(ofSize: 14)
        messageLabel.textColor = .gray
        messageLabel.textAlignment = .center
        messageLabel.numberOfLines = 0
        addSubview(messageLabel)
        
        messageLabel.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(10)
            make.left.right.equalToSuperview().inset(40)
        }
        
        // 按钮
        if let buttonTitle = wjDelegate.wjButtonTitle(for: state),
           !buttonTitle.isEmpty {
            let button = UIButton(type: .system)
            button.setTitle(buttonTitle, for: .normal)
            button.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .bold)
            button.setTitleColor(.white, for: .normal)
            button.backgroundColor = UIColor(hex: "#1E4FF3")
            button.layer.cornerRadius = 22
            button.layer.borderWidth = 1.0
            button.layer.borderColor = UIColor(hex: "#FFFFFF").cgColor
            button.addTarget(self, action: #selector(wjDidTapButton), for: .touchUpInside)
            addSubview(button)
            
            button.snp.makeConstraints { make in
                make.top.equalTo(messageLabel.snp.bottom).offset(30)
                make.centerX.equalToSuperview()
                make.width.equalTo(120)
                make.height.equalTo(44)
            }
        }
    }
    
    @objc private func wjDidTapButton() {
        wjDelegate?.wjDidTapStateButton()
    }
}
